﻿using System.Collections;
using System.Collections.Generic;
using System.Security.Permissions;
using AspNetInfo.Core;
using System.Data;
using System.Web;

namespace AspNetInfo.Detectors
{
    public class EnvironmentVariablesDetector : IDetector
    {
        public DataTable Detect(EnvironmentPermissions permissions)
        {
            if (permissions.TrustLevel > AspNetHostingPermissionLevel.Medium)
                return GetFullTrustEnvironmentVariables();
            else
                return GetMediumTrustEnvironmentVariables();
        }
        public string Name
        {
            get { return "Environment Variables"; }
        }

        public string Description
        {
            get { return string.Empty; }
        }

        public string TabName
        {
            get { return Tabs.General; }
        }

        private DataTable GetFullTrustEnvironmentVariables()
        {
            var dt = DetectorHelper.MakeResultTable();
            foreach (DictionaryEntry envVar in System.Environment.GetEnvironmentVariables())
            {
                dt.Rows.Add(envVar.Key.ToString(), envVar.Value.ToString());
            }
            return dt;
        }

        private DataTable GetMediumTrustEnvironmentVariables()
        {
            var dt = DetectorHelper.MakeResultTable();
            try
            {
                new EnvironmentPermission(
                 EnvironmentPermissionAccess.Read,
                 "TEMP;TMP;OS;USERNAME;COMPUTERNAME").Demand();
                dt.Rows.Add("TEMP", System.Environment.GetEnvironmentVariable("TEMP"));
                dt.Rows.Add("TMP", System.Environment.GetEnvironmentVariable("TMP"));
                dt.Rows.Add("OS", System.Environment.GetEnvironmentVariable("OS"));
                dt.Rows.Add("USERNAME", System.Environment.GetEnvironmentVariable("USERNAME"));
                dt.Rows.Add("COMPUTERNAME", System.Environment.GetEnvironmentVariable("COMPUTERNAME"));
            }
            catch (System.Security.SecurityException ex)
            {
                throw ex;
            }

            return dt;
        }
    }
}
